package ru.spb.osll.myfit.server.execute;

import ru.spb.osll.myfit.common.PageProgressCounts;
import ru.spb.osll.myfit.util.FileHelper;

import java.io.*;

public class PageWriter {
	private String head;
	private final String tail = "  </BODY>\n"
          + "</HTML>\n";
	private String m_pageName;
  private String m_src;

	public PageWriter(String pageName, String src) {
		m_pageName = pageName;
    m_src = src;
	}

	public void writeStream(ByteArrayOutputStream outputStream,
                            PageProgressCounts progressCounts) {
    (new FileHelper()).copyDir(m_src,
            (new File(m_pageName)).getParent() +
                    File.separator + "files");
		String strPage = outputStream.toString();
    try {
      outputStream.close();

      try {
    	  
    	strPage = replaceSomeSubstrings(strPage);
        FileOutputStream out = new FileOutputStream(m_pageName);
        try {
          OutputStreamWriter outwriter = new OutputStreamWriter(out, "windows-1251");
          PrintWriter writer = new PrintWriter(outwriter);
          setHead(progressCounts);
          writer.write(head);
          writer.write(strPage);
          writer.write(tail);
          writer.close();
          outwriter.close();
          out.close();

        } catch (UnsupportedEncodingException e) {
          out.close();
        }
      } catch (FileNotFoundException e) {

      }

    } catch (IOException e) {
    }

	}

    private void setHead (PageProgressCounts progressCounts) {
      head = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n"
              + "   \"http://www.w3.org/TR/html4/strict.dtd\">\n"
              + "<HTML>\n"
              + "  <HEAD>\n"
              + "    <title> processed: " + progressCounts.getProgressSegments()
              + ", right: " + progressCounts.getRight()
              + ", wrong: " + progressCounts.getWrong()
              + ", ignored: " + progressCounts.getIgnores()
              + ", exceptions: " + progressCounts.getExceptions()
              + "    </title>\n"
              + "    <LINK href=\"files" + File.separator + "css" + File.separator +
              "fitnesse_base.css\" rel=\"stylesheet\" type=\"text/css\">\n"
              + "    <SCRIPT src=\"files" + File.separator + "javascript"
              + File.separator + "fitnesse.js\"></SCRIPT>\n"
              + "  </HEAD>\n"
              + "  <BODY>\n";
    }
    
    private String replaceSomeSubstrings(String src){
    	return src.replaceAll("class=\"hidden\"", "class=\"collapsable\"");
    }
}
